package com.buaa.controller;

import com.buaa.model.db.User;
import com.buaa.model.dto.PersonDetail;
import com.buaa.model.solr.Person;
import com.buaa.service.PersonService;
import com.buaa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class SearchController {

    @Autowired
    PersonService personService;

    @RequestMapping(value = "/person" ,method = RequestMethod.GET)
    public String person(HttpServletRequest request, Model model) {
        String keyword = request.getParameter("keyword");
        model.addAttribute("keyword",keyword);

        String name = "";
        String organization = "";

        PersonDetail personDetail = new PersonDetail();

        String[] nameAndOrg = keyword.split(" ");
        if(nameAndOrg.length == 2){
            name = nameAndOrg[0];
            organization = nameAndOrg[1];
            Person person = personService.findPersonByNameAndOrg(name,organization);
            personDetail.setPerson(person);
        }else{
            name = nameAndOrg[0];
            List<Person> personList = personService.findPersonListByName(name);
            personDetail.setPerson(personList.get(0));
            personDetail.setOtherPerson(personList.subList(1,Math.min(10,personList.size())));
        }
        if(personDetail.getPerson() == null || personDetail.getPerson().getName() == null){
            return "no_person";
        }
        model.addAttribute("personDetail",personDetail);

        return "person";
    }

    @RequestMapping(value = "/organization" ,method = RequestMethod.GET)
    public String organization(HttpServletRequest request, Model model) {
        String keyword = request.getParameter("keyword");
        model.addAttribute("keyword",keyword);
        String organization = keyword;

        

        return "organization";
    }

    @RequestMapping(value = "/field" ,method = RequestMethod.GET)
    public String field(HttpServletRequest request, Model model) {
        return "field";
    }

    @RequestMapping(value = "/main" ,method = RequestMethod.GET)
    public String main(HttpServletRequest request, Model model) {
        return "main";
    }

}